import { ref, reactive, watch, type Ref } from 'vue'
import type { AxiosPromise } from 'axios'

// 分页参数类型
export interface PaginationParams {
  page: number
  size: number
}

// 分页返回结果类型
export interface PaginationResult<T> {
  records: T[]
  total: number
  [key: string]: any
}

// Hook配置选项
interface UsePaginationOptions<T> {
  /** 默认每页条数 */
  defaultPageSize?: number
  /** 是否自动加载初始数据 */
  autoLoad?: boolean
  /** 默认查询参数 */
  defaultParams?: Record<string, any>
  /** 数据转换器 */
  transformer?: (data: any) => T[]
}

// Hook返回类型
interface UsePaginationReturn<T> {
  /** 当前页码 */
  current: Ref<number>
  /** 每页条数 */
  size: Ref<number>
  /** 总条数 */
  total: Ref<number>
  /** 加载状态 */
  loading: Ref<boolean>
  /** 表格数据 */
  tableData: Ref<T[]>
  /** 查询参数 */
  queryParams: Ref<Record<string, any>>
  /** 加载数据方法 */
  loadData: () => Promise<void>
  /** 处理搜索 */
  handleSearch: () => void
  /** 重置分页 */
  resetPagination: () => void
}

/**
 * 分页数据管理Hook
 * @param fetchData 获取数据的异步方法
 * @param options 配置选项
 */
export function usePagination<T = any>(
  fetchData: (params: PaginationParams & Record<string, any>) => AxiosPromise<PaginationResult<T>>,
  options: UsePaginationOptions<T> = {}
): UsePaginationReturn<T> {
  // 合并配置选项
  const {
    defaultPageSize = 10,
    autoLoad = true,
    defaultParams = {},
    transformer
  } = options

  // 状态定义
  const current = ref(1)
  const size = ref(defaultPageSize)
  const total = ref(0)
  const loading = ref(false)
  const tableData = ref<T[]>([]) as Ref<T[]>
  const queryParams = ref<Record<string, any>>({ ...defaultParams })

  // 核心方法：加载数据
  const loadData = async () => {
    try {
      loading.value = true
      const params = {
        page: current.value,
        size: size.value,
        ...queryParams.value
      }

      const { data } = await fetchData(params)
      tableData.value = transformer ? transformer(data.records) : data.records
      total.value = data.total
    } catch (error) {
      console.error('分页数据加载失败:', error)
      tableData.value = []
      total.value = 0
    } finally {
      loading.value = false
    }
  }

  // 处理搜索（重置页码）
  const handleSearch = () => {
    current.value = 1
    loadData()
  }

  // 重置分页状态
  const resetPagination = () => {
    current.value = 1
    size.value = defaultPageSize
    queryParams.value = { ...defaultParams }
  }

  // 监听页码/页数变化自动加载
  watch([current, size], () => {
    loadData()
  }, { immediate: autoLoad })

  return {
    current,
    size,
    total,
    loading,
    tableData,
    queryParams,
    loadData,
    handleSearch,
    resetPagination
  }
}